<template>
  <div
    class="t-form-wrap"
    v-show="mappingProps.visible"
    :class="{ 'z-design': inDesign }"
    tabIndex="-1"
  >
    <q-form
      class="t-form"
      ref="formCpt"
      v-bind="{ ...attrs, ...mappingProps }"
      :tabindex="undefined"
      @submit="submit"
      @loaded="loaded"
      @validation-error="v => emit('validationError', v)"
      @validation-success="v => emit('validationSuccess', v)"
    >
      <slot></slot>
    </q-form>
  </div>
</template>

<script setup type="typescript">
// <!-- ts只是方便开发提示和补全代码，没有用语法 -->

import { computed, onMounted, ref, useAttrs, useSlots, watchEffect } from 'vue';
// 钩子方法
import useMappingProps from 't/common/hooks/useMappingProps';
import {
	commonProps
} from 't/common/utils';
// 组件
import QForm from '@teld/q-components/Form';

// 直接映射透传qursor的属性
const attrs = useAttrs();
// 组件传参
const props = defineProps(
	// 大小写不敏感
	{
		...commonProps,
		...QForm.props,

		// 默认可见
		visible: {
			type: Boolean,
			default: true,
		},

		// Loaded事件后置
		delayOnLoaded: {
			type: Boolean,
			default: false,
		},

		noResetFocus: {
			type: Boolean,
			default: false,
		},

		autofocus: {
			type: Boolean,
			default: false,
		},

		tabIndex: '-1'
	}
);

// 大写首字母属性
const [mappingProps, mappingExpose] = useMappingProps(props);

// 是否设计时
const inDesign = ref(!!window['fas']?.inDesign);

// ============================= 回调事件 ===========================
// 触发的emit事件
const emit = defineEmits(['loaded', 'submit', 'reset', 'validationSuccess', 'validationError']);

// ============================= 暴漏外部方法 ===========================
const formCpt = ref(null);
function submit(e) {
	emit('submit', e)
}
function loaded(e) {
	emit('loaded', e)
}
function reset() {
	// formCpt.value.resetValidation();
	formCpt.value.reset();
	emit('reset')
}
function validate() {
	return formCpt.value.validate()
}
// 暴漏外部方法
defineExpose({
	...mappingExpose,
	validate,
	submit,
	loaded,
	reset,
	focus() {
		formCpt.value.focus()
	},
	resetValidation: v => formCpt.value.resetValidation(v),
	getValidationComponents: v => formCpt.value.getValidationComponents(v),
});

// 挂载生命钩子
onMounted(() => {
	if (!mappingProps.delayOnLoaded) loaded();
})
</script>

<style lang="scss">
.t-form-wrap {
  &.z-design {
    border: 1px dashed #67c23a;

    &::before {
      content: 'Form表单（仅在设计时显示此提示）';
      display: block;
      color: #67c23a;
      line-height: 30px;
      padding-left: 2px;
      background-color: #f7f8f9;
      overflow: hidden;
    }
  }
}
</style>
